﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace DG.Common.EF.WPF
{
    /// <summary>
    /// Interaction logic for EntityListViewerWindow.xaml
    /// </summary>
    public partial class EntityListViewerWindow : Window
    {
        public EntityListViewerWindow(EntityListViewerModel vm)
        {
            InitializeComponent();


            DataContext = vm;

            vm.Finished += Close;
            vm.MessageSent += s => MessageBox.Show(s);
        }

        private void ButoonSelecionar_OnClick(object sender, RoutedEventArgs e)
        {
            if (((EntityListViewerModel)DataContext).SelectedEntity == null) return;
            _lancamentoEscolhido = ((EntityListViewerModel)DataContext).SelectedEntity;
            Close();
            
        }
        private object _lancamentoEscolhido;
        public static T Escolher<T>(Func<IDbContext> ctx) where T:class 
        {
            var vm = new EntityListViewerModel(ctx, typeof (T));
            var wnd = new EntityListViewerWindow(vm) { ButoonSelecionar = { Visibility = Visibility.Visible } };
            wnd.ShowDialog();
            return wnd._lancamentoEscolhido == null ? null : (T)wnd._lancamentoEscolhido;
        }

        private void DataGrid_OnAutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            var vm = ((EntityListViewerModel)DataContext);
            var propertyMeta = vm.ConceptualInfos.EntitiesConceptualInfos[vm.Type].PropertiesMeta.Values.SingleOrDefault(p => p.Name == e.PropertyName);
            if (propertyMeta == null)
                propertyMeta = vm.ConceptualInfos.EntitiesConceptualInfos[vm.Type].PropertiesMeta.Values.SingleOrDefault(p => p.DisplayName == e.PropertyName);

            if (propertyMeta != null && (propertyMeta.IsKey && propertyMeta.IsAutoIncrement))
                e.Cancel = true;
        }
    }
}
